package com.example.util;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.beust.jcommander.internal.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author long
 * @date 2024/11/20 9:43
 */
public class TestOptionals {

    public static void main(String[] args) {

        // 和Optional比较
        Dog dog = new Dog(1L,"tom");

        // 判空打印对象
        Optional.ofNullable(dog).ifPresent(System.out::println);
        Optionals.ofNullable(dog, Objects::nonNull).ifPresent(System.out::println);

        // 获取对应的name值
        String name1 = Optional.ofNullable(dog).map(Dog::getName).orElse(null);
        System.out.println(name1);

        String name2 = Optionals.ofNullable(dog,Objects::nonNull).map(Dog::getName, StringUtils::isNotBlank).orElse(null);
        System.out.println(name2);

        String name3 = Optional.of(dog).map(Dog::getName).filter(StringUtils::isNotBlank).orElse(null);
        System.out.println(name3);

        // Optionals更加灵活,不仅支持 ！=null判断，还支持所有的断言型判断
        List<Dog> dogList = Lists.newArrayList(dog);
        String dogName = Optionals.ofNullable(dogList, CollectionUtils::isNotEmpty)
                            .map(l->l.get(0),Objects::nonNull)
                                .map(Dog::getName,StringUtils::isNotBlank).orElseGet(()-> null);
        System.out.println(dogName);

    }

    @Data
    @AllArgsConstructor
    static class Dog{

        private Long id;

        private String name;

    }

}
